package co.yixiang.hw.service.impl;

import co.yixiang.hw.domain.YxWechatUser;
import co.yixiang.utils.ValidationUtil;
import co.yixiang.utils.FileUtil;
import co.yixiang.hw.repository.YxWechatUserRepository;
import co.yixiang.hw.service.YxWechatUserService;
import co.yixiang.hw.service.dto.YxWechatUserDto;
import co.yixiang.hw.service.dto.YxWechatUserQueryCriteria;
import co.yixiang.hw.service.mapper.YxWechatUserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import co.yixiang.utils.PageUtil;
import co.yixiang.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;


/**
 * @author Walert
 * @date 2020-05-19
 */
@Service
//@CacheConfig(cacheNames = "yxWechatUser")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxWechatUserServiceImpl implements YxWechatUserService {

    @Resource
    private YxWechatUserRepository yxWechatUserRepository;
    @Resource
    private YxWechatUserMapper yxWechatUserMapper;


    @Override
    //@Cacheable
    public Map<String,Object> queryAll(YxWechatUserQueryCriteria criteria, Pageable pageable){
        Page<YxWechatUser> page = yxWechatUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(yxWechatUserMapper::toDto));
    }

    @Override
    //@Cacheable
    public List<YxWechatUserDto> queryAll(YxWechatUserQueryCriteria criteria){
        return yxWechatUserMapper.toDto(yxWechatUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    //@Cacheable(key = "#p0")
    public YxWechatUserDto findById(Integer uid) {
        YxWechatUser yxWechatUser = yxWechatUserRepository.findById(uid).orElseGet(YxWechatUser::new);
        ValidationUtil.isNull(yxWechatUser.getUid(),"YxWechatUser","uid",uid);
        return yxWechatUserMapper.toDto(yxWechatUser);
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public YxWechatUserDto create(YxWechatUser resources) {
        return yxWechatUserMapper.toDto(yxWechatUserRepository.save(resources));
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(YxWechatUser resources) {
        YxWechatUser yxWechatUser = yxWechatUserRepository.findById(resources.getUid()).orElseGet(YxWechatUser::new);
        ValidationUtil.isNull( yxWechatUser.getUid(),"YxWechatUser","id",resources.getUid());
        yxWechatUser.copy(resources);
        yxWechatUserRepository.save(yxWechatUser);
    }

    @Override
    //@CacheEvict(allEntries = true)
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            yxWechatUserRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<YxWechatUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YxWechatUserDto yxWechatUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段", yxWechatUser.getUnionid());
            map.put("用户的标识，对当前公众号唯一", yxWechatUser.getOpenid());
            map.put("小程序唯一身份ID", yxWechatUser.getRoutineOpenid());
            map.put("用户的昵称", yxWechatUser.getNickname());
            map.put("用户头像", yxWechatUser.getHeadimgurl());
            map.put("用户的性别，值为1时是男性，值为2时是女性，值为0时是未知", yxWechatUser.getSex());
            map.put("用户所在城市", yxWechatUser.getCity());
            map.put("用户的语言，简体中文为zh_CN", yxWechatUser.getLanguage());
            map.put("用户所在省份", yxWechatUser.getProvince());
            map.put("用户所在国家", yxWechatUser.getCountry());
            map.put("公众号运营者对粉丝的备注，公众号运营者可在微信公众平台用户管理界面对粉丝添加备注", yxWechatUser.getRemark());
            map.put("用户所在的分组ID（兼容旧的用户分组接口）", yxWechatUser.getGroupid());
            map.put("用户被打上的标签ID列表", yxWechatUser.getTagidList());
            map.put("用户是否订阅该公众号标识", yxWechatUser.getSubscribe());
            map.put("关注公众号时间", yxWechatUser.getSubscribeTime());
            map.put("添加时间", yxWechatUser.getAddTime());
            map.put("一级推荐人", yxWechatUser.getStair());
            map.put("二级推荐人", yxWechatUser.getSecond());
            map.put("一级推荐人订单", yxWechatUser.getOrderStair());
            map.put("二级推荐人订单", yxWechatUser.getOrderSecond());
            map.put("佣金", yxWechatUser.getNowMoney());
            map.put("小程序用户会话密匙", yxWechatUser.getSessionKey());
            map.put("用户类型", yxWechatUser.getUserType());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void asyncSaveWechatUserInfo(Integer uid, JSONObject userInfo) {
        Long addTime = System.currentTimeMillis()/1000L;
        if(userInfo != null){
            Optional<YxWechatUser> byId = yxWechatUserRepository.findById(uid);
            YxWechatUser weChatUser = new YxWechatUser();
            weChatUser.setUid(uid);
            if(byId.isPresent()){
                weChatUser = byId.get();
            }
            weChatUser.setAddTime(addTime.intValue());
            weChatUser.setCity(userInfo.getString("city"));
            weChatUser.setCountry(userInfo.getString("country"));
            weChatUser.setHeadimgurl(userInfo.getString("avatarUrl"));
            weChatUser.setLanguage(userInfo.getString("language"));
            weChatUser.setNickname(userInfo.getString("nickName"));
            weChatUser.setProvince(userInfo.getString("province"));
            weChatUser.setOpenid(userInfo.getString("openId"));
            weChatUser.setUnionid(userInfo.getString("unionId"));
            weChatUser.setSex(userInfo.getInteger("gender"));
            weChatUser.setUserType("wechat");
            yxWechatUserRepository.saveAndFlush(weChatUser);
        }
    }
}